package leetcode.D100.T2;

import util.ListNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: DYZ
 * @Create: 2021-08-06 17:00:48 星期五
 */

public class Solution {
    // 一刷
    /*public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if((l1.val == 0 && l1.next == null) || (l2.val == 0 && l2.next == null)) {
            return (l1.val == 0 && l1.next == null) ? l2 : l1;
        }
        ListNode head = new ListNode();
        ListNode p1 = l1, p2 = l2, p = head, q = head;
        int carry = 0;
        while(p1 != null && p2 != null) {
            int sum = p1.val + p2.val + carry;
            carry = sum / 10;
            p = new ListNode();
            p.val = sum % 10;
            q.next = p;
            q = p;
            p1 = p1.next;
            p2 = p2.next;
        }
        p1 = p1 == null ? p2 : p1;
        while(p1 != null || carry > 0) {
            int sum = p1 != null ? p1.val + carry : carry;
            carry = sum / 10;
            p = new ListNode();
            p.val = sum % 10;
            q.next = p;
            q = p;
            p1 = p1 != null ? p1.next : null;
        }
        return head.next;
    }*/

    // 二刷
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0, l1), p = head;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int sum = carry + l1.val + l2.val;
            p.next.val = sum % 10;
            carry = sum / 10;
            l1 = l1.next;
            l2 = l2.next;
            p = p.next;
        }
        if (l1 == null)
            p.next = l2;
        while (carry > 0 && p.next != null) {
            int sum = carry + p.next.val;
            p.next.val = sum % 10;
            carry = sum / 10;
            p = p.next;
        }
        if (carry > 0)
            p.next = new ListNode(carry);
        return head.next;
    }
}
